<!--
  论坛详情页
  sy
  2020年2月10日
-->

<template lang="pug">
  el-container
    el-header.header
      title-bg(moduleTitle="在线论坛")
    el-container
      el-aside.nav-layout(width="258px")
        nav-menu
      el-main#mainContentBox
        main-content(modularTitle="在线论坛")
        div.main-content-box
          p.main-content-title Online BBS
          el-row(:gutter="28")
            el-col(:span="16")
              el-card.post-box
                div(slot="header").card-title.clearfix 论坛列表
                  el-button.blueBtn(@click="repeatAuthor") 我要回复
                div.forum-articles
                  table.forumReply-box(v-for="item in landlord" cellpadding="0" cellspacing="0" v-if="currentPage===1")
                    tr
                      td.forumReply-L
                        img(:src="item.headportrait")
                        span.replyName {{item.userName}}
                        span.replyCalling {{item.identity}}
                        div.replyMessage {{item.hospitalName}}丨{{item.title}}
                      td.forumReply-R
                        div.forumReply-Rtop.clearfix
                          div.textMessage-title.clearfix
                            span.btn-zd(v-if="item.messageFlag") [置顶]
                            span.btn-jp(v-if="item.messageJingFlag") [精品]
                            span.classification {{item.theme}}
                            h4 {{item.messageTitle}}
                          span.replyTime 发表于 {{item.messageDateTime}} 丨 查看({{item.browsenum}}) 丨 回复({{item.replynum}})
                          span.replyFloor 楼主
                        div.forumReply-Rmiddle
                          span(v-html="item.messageContent") {{item.messageContent}}
                          p.myScoringP 我的评分：
                            el-rate.myScoring(v-model="myScoring" show-score score-template="{value}分" :disabled="rateDisabled")
                            el-button.btnScoring(type="warning" @click="rate" :disabled="rateDisabled") 提交评价
                          div.imgs.float-left(v-for="img in item.photo" @click="imgPreview(img)" v-if="img")
                            img(:src="img")
                          div.clear
                          el-dialog(:visible.sync="dialogVisible")
                            img(width="100%" :src="dialogImageUrl")
                          div.files
                            span 附件:
                            div.file-box(v-for="fileItem in item.file" @click="download(fileItem)" v-if="fileItem")
                              img(src="~@/assets/img/forum/file.png")
                              p {{fileItem | ellipsis}}
                            span(v-else) 暂无附件
                          div.video-box
                            video(
                              v-for="videoItem in item.uploadVideo"
                              ref="video"
                              v-if="videoItem"
                              controls
                              preload="auto"
                            )
                        div.forumReply-Rbottom.clearfix
                          span.postScoringSpn 本贴平均分：
                          el-rate.postScoring(v-model="postScoring" disabled show-score text-color="#ff9900" score-template="{value}")
                          span.replyBtn
                            i.el-icon-edit(@click="repeatAuthor") &nbsp;回复
                  table.forumReply-box(v-for="(item, index) in forumList" :key="index" cellpadding="0" cellspacing="0")
                    tr
                      td.forumReply-L
                        img(:src="item.headportrait")
                        span.replyName {{item.userName}}
                        span.replyCalling {{item.identity}}
                        div.replyMessage {{item.hospitalName}}丨{{item.title}}
                      td.forumReply-R
                        div.forumReply-Rtop.clearfix
                          span.replyTime 发表于 {{item.messageDateTime}}
                          span.replyFloor {{currentPage-1===0? null : currentPage-1}}{{index + 1}}楼
                        div.forumReply-Rmiddle
                          p.replyTitle(v-if="item.repeatName") {{item.userName}} 回复 {{item.repeatName}}
                          p(v-html="item.replyMessage") {{item.replyMessage}}
                        div.forumReply-Rbottom.clearfix
                          span.replyBtn(@click="showToggle(item)")
                            i.el-icon-edit {{item.btnText}}
                          div.textareaBox(v-if="item.isShow")
                            textarea.replyTextarea(v-model="item.replyTextarea")
                            el-button(type="primary" @click="repeat(item)") 回复
                div.topPage.clearfix
                  el-pagination.pagination(
                    layout="prev,pager,next,total,jumper"
                    :hide-on-single-page= "true"
                    :total="total"
                    background
                    :current-page="currentPage"
                    :page-size="10"
                    prev-text="上一页"
                    next-text="下一页"
                    @current-change="handleCurrentChange"
                    @prev-click="handlePrevClick"
                    @next-click="handleNextClick"
                  )
                TinyEditer(ref="editor").editor#editor
                el-button.submitBtn(type="primary" @click="submit") 提交
                div.clear
            el-col(:span="8")
              el-card.form-card
                div(slot="header").card-title 热门帖子
                div(ref="popularBox").popular-box
                  ul.popularUl
                    li.clearfix(v-for="(item, index) in popularList" @click="toForum(item)" v-show="index<10")
                      span.discSpan
                      span.popularTitle {{item.messageTitle}}
</template>

<script>
  import TitleBg from '../../components/TitleBg'
  import NavMenu from '../../components/NavMenu'
  import MainContent from '../../components/MainContent'
  import {baseURL} from '../../config/global.toml'

  export default {
    components: {
      MainContent,
      TitleBg,
      NavMenu
    },
    name: 'ForumDetsils',
    data() {
      return {
        fullHeight: document.documentElement.clientHeight, // 屏幕可视区域高度
        landlord: [], // 楼主数据
        forumList: [], // 帖子回复数据
        total: null, // 回帖总数null
        currentPage: 1, // 当前页数
        postScoring: null, // 当前帖子平均分
        myScoring: null, // 我的评分
        tinymceHtml: '', // 回复楼主文本
        rateDisabled: false, // 评分是否禁用
        dialogVisible: false, // 图片预览状态
        dialogImageUrl: '', // 图片预览中图片路径
        popularList: [], // 热门列表
        identity: [],
        forumId: null
      }
    },
    mounted() {
      let that = this
      window.onresize = () => {
        return (() => {
          window.fullHeight = document.documentElement.clientHeight
          that.fullHeight = window.fullHeight
          that.$nextTick(() => {
            that.$refs.popularBox.style.height = that.fullHeight - 278 - 42 + 'px' // 热门帖子高度
          })
        })()
      }
      this.$nextTick(() => {
        that.$refs.popularBox.style.height = that.fullHeight - 278 - 42 + 'px' // 热门帖子高度
      })
      this.identity = JSON.parse(this.$KalixCatch.get('personaltwo'))
      // 页面渲染完成获取相关数据
      setTimeout(() => {
        this.getLandlordData()
        this.getDetailsData(1)
        this.getPopular()
      }, 500)
    },
    watch: {
      // 监听屏幕可视区域高度变化
      fullHeight(val) {
        // 为了避免频繁触发resize函数导致页面卡顿，使用定时器
        if (!this.timer) {
          // 一旦监听到的fullHeight值改变，就将其重新赋给data里的fullHeight
          this.fullHeight = val
          this.timer = true
          let that = this
          setTimeout(function () {
            that.timer = false
          }, 400)
        }
      },
      // '$route': function (newUrl, oldUrl) {
      //   if (newUrl !== oldUrl) {
      //     this.routerKey = this.$route.query.forumId
      //     console.log(this.routerKey)
      //   }
      // }
      $route() {
        this.forumId = this.$route.query.forumId
      },
      forumId() {
        let that = this
        window.onresize = () => {
          return (() => {
            window.fullHeight = document.documentElement.clientHeight
            that.fullHeight = window.fullHeight
            that.$nextTick(() => {
              that.$refs.popularBox.style.height = that.fullHeight - 278 - 33 + 'px' // 热门帖子高度
            })
          })()
        }
        this.$nextTick(() => {
          that.$refs.popularBox.style.height = that.fullHeight - 278 + 'px' // 热门帖子高度
        })
        this.identity = JSON.parse(this.$KalixCatch.get('personaltwo'))
        // 页面渲染完成获取相关数据
        setTimeout(() => {
          this.getLandlordData()
          this.getDetailsData(1)
          this.getPopular()
        }, 500)
      }
    },
    filters: {
      // 文件名称过滤
      ellipsis(value) {
        value = value.split('/')
        value = value[value.length - 1]
        return value
      }
    },
    methods: {
      /**
       * 前后台交互
       */
      // 获取楼主数据
      getLandlordData() {
        this.$http.request({
          method: 'GET',
          url: '/camel/rest/telemedicine/messages/getForumdetails',
          params: {
            id: this.$route.query.forumId
          }
        }).then(res => {
          let _data = res.data.data
          console.log('------Landlord------', _data)
          _data[0].file = _data[0].file.split(',')
          _data[0].photo = _data[0].photo.split(',')
          _data[0].uploadVideo = _data[0].uploadVideo.split(',')
          this.landlord = _data
          this.postScoring = parseInt(_data[0].scoreArray)
          setTimeout(() => {
            this.$refs.video.forEach((item, i) => {
              item.src = this.landlord[0].uploadVideo[i]
            }, 400)
          })
          this.getIsScroe()
        })
      },
      // 获取回帖数据
      getDetailsData(val) {
        this.$http.request({
          method: 'GET',
          url: '/camel/rest/telemedicine/messagereplys/getMessageReplyPostinglist',
          params: {
            num: val,
            id: this.$route.query.forumId
          }
        }).then(res => {
          let _data = res.data.data
          this.total = res.data.totalCount
          console.log('------Forumdetails------', _data)
          // _data.map(item => {
          //   return Object.assign(item, {btnText: '回复', isShow: false, replyTextarea: ''})
          // })
          _data.forEach((item) => {
            item.btnText = '回复'
            item.isShow = false
            item.replyTextarea = ''
          })
          this.forumList = _data
        })
      },
      // 根据返回数据判断当前用户是否已评价
      getIsScroe() {
        this.$http.request({
          method: 'GET',
          url: '/camel/rest/telemedicine/messagereplys/judgeIsScore',
          params: {
            id: this.$route.query.forumId,
            userId: this.identity[0].id
          }
        }).then(res => {
          let _data = res.data
          console.log('------IsScroe------', _data)
          this.rateDisabled = _data.totalCount !== 0
          this.myScoring = _data.data[0].fraction
        })
      },
      // 当前用户对帖子进行评分并发送到后台
      sendRateData(callback) {
        this.$http.request({
          method: 'GET',
          url: '/camel/rest/telemedicine/messages/getFraction',
          params: {
            id: this.$route.query.forumId,
            fraction: this.myScoring
          }
        }).then(res => {
          callback()
        })
      },
      // 评分
      getFraction() {
        this.$http.request({
          method: 'GET',
          url: '/camel/rest/telemedicine/messages/getFraction',
          params: {
            id: this.id,
            fraction: this.myScoring
          }
        }).then(res => {
        })
      },
      // 将回复楼主的内容发送至后台
      sendRepeatAuthorData() {
        this.$http.request({
          method: 'GET',
          url: '/camel/rest/telemedicine/messagereplys/getReplyMessage',
          params: {
            userName: this.identity[0].name,
            messageId: this.$route.query.forumId,
            replyMessage: this.$refs.editor.tinymceHtml,
            photo: null,
            headportrait: this.identity[0].icon,
            identity: this.identity[0].identity,
            judgeIsScore: true,
            userId: this.identity[0].id,
            fraction: this.myScoring
          }
        }).then(res => {
        })
      },
      // 将帖子ID发送至后台回复+1
      sendForumID() {
        this.$http.request({
          method: 'GET',
          url: '/camel/rest/telemedicine/messages/getreplynum',
          params: {
            id: this.$route.query.forumId
          }
        }).then(res => {
        })
      },
      // 发送回复其他楼层内容数据
      sendCommentData(item, callback) {
        this.$http.request({
          method: 'GET',
          url: '/camel/rest/telemedicine/messagereplys/getComment',
          params: {
            uid: this.identity[0].id,
            userName: this.identity[0].name,
            messageId: this.$route.query.forumId,
            replyMessage: item.replyTextarea,
            photo: null,
            replyID: item.id,
            headportrait: this.identity[0].icon,
            identity: this.identity[0].identity,
            repeatName: item.userName
          }
        }).then(res => {
          callback()
        })
      },
      // 获取热门发帖
      getPopular() {
        this.$http.request({
          method: 'GET',
          url: 'camel/rest/telemedicine/messages/getPopular' // 查询共有多少条帖子
        }).then(res => {
          let _data = res.data.data
          console.log('------Popular------', _data)
          this.popularList = _data
        })
      },
      // 根据帖子ID跳转详情页
      toForum(item) {
        this.$router.push({path: '/forum/forumDetails', query: {forumId: item.id}})
        this.$http.request({
          method: 'GET',
          url: '/camel/rest/telemedicine/messages/getbrowsenum',
          params: {
            id: item.id
          }
        }).then(res => {
        })
      },
      /**
       *页面事件
       */
      // 文件下载
      download(fileName) {
        let urls = baseURL + '/outline/download?file=' + fileName
        window.location.href = urls
      },
      // 图片预览
      imgPreview(imgUrl) {
        this.dialogImageUrl = imgUrl
        this.dialogVisible = true
      },
      // 切换当前页
      handleCurrentChange(val) {
        console.log('当前页', val)
        this.currentPage = val
        this.getDetailsData(this.currentPage)
      },
      // 前一页
      handlePrevClick() {
        this.currentPage--
        this.getDetailsData(this.currentPage)
      },
      // 后一页
      handleNextClick() {
        this.currentPage++
        this.getDetailsData(this.currentPage)
      },
      // 切换回复按钮
      showToggle(item) {
        item.isShow = !item.isShow
        if (item.isShow === true) {
          item.btnText = '收回回复'
        } else {
          item.btnText = '回复'
        }
      },
      // 回复其他楼层
      repeat(item) {
        this.sendCommentData(item,
          () => this.getDetailsData(this.currentPage)
        )
        this.sendForumID()
        item.replyTextarea = ''
        item.isShow = false
      },
      // 回复楼主
      repeatAuthor() {
        let editor = document.getElementById('editor')
        let mainContentBox = document.getElementById('mainContentBox')
        console.log(editor.offsetTop)
        this.$nextTick(() => {
          mainContentBox.scrollTop = editor.offsetTop
        })
      },
      // 回复楼主提交按钮
      submit() {
        this.sendRepeatAuthorData()
        this.sendForumID()
        this.$refs.editor.tinymceHtml = null
        this.$router.go(0)
      },
      // 提交评价
      rate() {
        this.sendRateData(data => {
          this.getLandlordData()
          this.getFraction(true)
        })
        this.rateDisabled = true
        // this.myScoring = 0
      }
    }
  }
</script>

<style scoped lang="stylus">
  .header
    padding 0

  .nav-layout
    position relative
    height 100%

  .clearfix
    zoom 1

  .clearfix:after
    clear both
    display block
    visibility hidden
    height 0
    line-height 0
    content ''

  .main-content-box
    padding-right 27px
    margin-top 28px

  .main-content-box .main-content-title
    color #a2c8f8
    font-size 14px

  .main-content-box .el-card
    margin-top 25px

  .main-content-box .el-card .card-title
    font-size 16px

  .textMessage-title .classification
    float left
    margin-right 4px
    cursor pointer

  .textMessage-title h4
    float left
    cursor pointer
    width 450px
    white-space nowrap
    overflow hidden
    text-overflow ellipsis
    font-weight normal

  .textMessage-title .classification:hover,
  .textMessage-title h4:hover
    color #1572e9

  .textMessage-information
    color #999
    height 28px
    line-height 28px
    font-size 14px

  .textMessage-information .carveUp
    margin 0 5px

  .el-pagination
    margin-top 20px
    text-align center

  .popularUl li
    font-size 14px
    color #676767
    line-height 61px
    height 61px
    white-space nowrap
    padding 0 30px

  .popularUl li:nth-child(even)
    background-color #f2f2f2

  .discSpan
    width 8px
    height 8px
    float left
    background-color #b7b8ba
    border-radius 50%
    margin 26px 20px 26px 0

  .popularTitle
    float left
    width 90%
    overflow hidden
    text-overflow ellipsis
    cursor pointer

  .popularTitle:hover
    color #1572e9

  .blueBtn
    float right
    line-height 28px
    padding 0 16px
    border-radius 17px
    margin-top -5px
    border-color #6bbbfa
    color #6bbbfa

  .blueBtn:hover
    background-color #6bbbfa
    color #fff

  /*论坛详情*/
  .forumCentral .topPage
    margin 20px 0

    .posting
      width 74px
      height 28px
      text-align center
      line-height 28px
      color #fff
      background-color #25a9e1
      border-radius 5px
      cursor pointer
      float left

  .forumCentral .topPage .el-pagination
    float right

  /* 用户回复 */
  .forumReply-box
    width 100%
    -webkit-box-sizing border-box
    box-sizing border-box
    border 1px solid #ccc
    margin-bottom 10px

  .forumReply-box .forumReply-L
    -webkit-box-sizing border-box
    box-sizing border-box
    width 160px
    border-right 1px dashed #ccc
    background-color aliceblue
    text-align center
    height 100%
    vertical-align top

  .forumReply-box .forumReply-L img
    width 120px
    height 120px
    display block
    margin 20px auto 10px
    border 1px solid #ccc
    padding 3px
    -webkit-box-sizing border-box
    box-sizing border-box
    background-color #fff

  .forumReply-box .forumReply-L span
    display block
    text-align center
    color #333
    font-size 16px

  .forumReply-box .forumReply-L .replyCalling
    color #fff
    font-size 14px
    margin-top 8px
    margin-bottom 14px
    background-color #25a9e1
    display inline-block
    padding 1px 4px
    border-radius 4px

  .forumReply-box .forumReply-L .replyMessage
    margin 0 auto 20px
    color #c3c3c3
    font-size 14px
    width 130px

  .forumReply-box .forumReply-R
    vertical-align top

  .forumReply-Rtop,
  .forumReply-Rmiddle,
  .forumReply-Rbottom
    border-bottom 1px dashed #ccc
    padding 20px
    line-height 20px
    font-size 14px

  .forumReply-Rtop .replyFloor
    float right
    font-size 14px

  .forumReply-Rmiddle
    min-height 142px

  .forumReply-Rbottom
    border-bottom none

  .forumReply-Rbottom .replyBtn
    float right
    cursor pointer
    line-height 20px

  .forumReply-Rbottom .postScoringSpn,
  .forumReply-Rbottom .postScoring
    float left

  .forumReply-Rtop h2
    line-height 34px

  .textareaBox
    clear both

  .textareaBox .replyTextarea
    width 100%
    resize none
    height 60px
    line-height 18px
    box-sizing border-box
    margin-top 6px

  .textareaBox .el-button,
  .submitBtn
    height 28px
    line-height 28px
    padding 0 20px
    font-size 12px
    float right
    margin 6px 0

  .myScoringP
    background-color oldlace
    padding 14px 20px 20px 20px
    font-size 20px
    line-height 28px
    margin-top 20px
    position relative

  .myScoringP .btnScoring
    position absolute
    top 20px
    right 20px

  .replyTitle
    background-color oldlace
    padding 10px
    font-size 14px
    margin 10px 0
    font-weight bold

  .file-box
    display inline-block
    vertical-align top
    margin 0 5px
    cursor pointer

    img
      display block
      width 48px
      margin 0 auto

  .imgs
    display flex
    width 100px
    height 150px
    border 1px solid #ccc
    padding 5px
    margin 5px
    align-items center

    img
      max-width 100%
      max-height 100%
      cursor pointer

  .textMessage-title
    height 30px
    line-height 30px

  .textMessage-title span
    float left
    font-size 16px
    margin-right 4px

  .btn-zd
    color #de1211

  .btn-jp
    color #ee6904

  .textMessage-title h4
    float left
    cursor pointer
    width 70%
    font-size 16px
    white-space nowrap
    overflow hidden
    text-overflow ellipsis
    font-weight normal

  .replyTime
    font-size 14px

  .topPage
    margin-bottom 20px

  ::-webkit-scrollbar-track-piece { /*滚动条凹槽的颜色，还可以设置边框属性*/
    background-color #f8f8f8
  }

  ::-webkit-scrollbar { /*滚动条的宽度*/
    width 4px
    height 9px
  }

  ::-webkit-scrollbar-thumb { /*滚动条的设置*/
    background-color #dddddd
    background-clip padding-box
    min-height 28px
  }

  ::-webkit-scrollbar-thumb:hover {
    background-color #bbb
  }

  .post-box
    margin-bottom 40px

  .video-box
    video
      width 100%

  .popular-box
    overflow auto
</style>
